/**
 *
 */
package anysware.core.dao.hibernate;

import java.io.Serializable;
import java.util.Collection;

import org.apache.commons.lang.Validate;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import anysware.core.dao.GenericDao;

/**
 * TODO: doc me
 *
 * @author keke<keke@codehaus.org>
 * @revision $Revision: 107 $
 * @version 0.0.1
 */
public class GenericHibernateDao<E, ID extends Serializable> extends
        HibernateDaoSupport implements GenericDao<E, ID> {
	protected Class<E>	clazz;

	public GenericHibernateDao(final Class<E> clazz) {
		super();
		this.clazz = clazz;
	}

	public GenericDao<E, ID> delete(final E entity) {
		Validate.notNull(entity);
		currentSession().delete(entity);
		return this;
	}

	public E get(final ID id) {
		Validate.notNull(id);
		return (E) currentSession().get(clazz, id);
	}

	public Collection<E> getByExample(final E e) {
		return currentSession().createCriteria(clazz).add(Example.create(e))
		        .list();
	}

	public E getOnlyByExample(final E e) {
		return (E) currentSession().createCriteria(clazz)
		        .add(Example.create(e)).setMaxResults(1).uniqueResult();
	}

	public Collection<E> listAll() {
		return currentSession().createCriteria(clazz).list();
	}

	public GenericDao<E, ID> save(final E entity) {
		currentSession().saveOrUpdate(entity);
		return this;
	}

	protected Session currentSession() {
		return getSessionFactory().getCurrentSession();
	}

}
